﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using SgLib;

// 关卡管理
public class CheckHit : MonoBehaviour
{
    public static event System.Action LevelFailed;
    public static event System.Action LevelCompleted;

    public PickRandom pickRandom;

    public LayerMask layer;
    // 已命中计数
    public int hitCount = 0;
    // 通关次数
    public int numberOfWinning = 0;
    // 当前关卡需要命中的目标数量
    public int numberOfHit;
    // 是否失败
    bool isFail = false;
    // 图片是否可以点击
    public bool isClick = true;
    private GameObject[] PicList
    {
        get
        {
            return GameObject.FindGameObjectsWithTag("FocusGameObject");
        }
    }

    public void Init()
    {
        this.hitCount = 0;
        this.numberOfWinning = 0;
        this.numberOfHit = 0;
        this.isFail = false;
        CheckHowManyHit();
        pickRandom.Init();

        isClick = false;//初始化
        Invoke("delaySetClick", 2f);
    }

    
    void Update()
    {
        ScreenMouseRay();
    }

    public void Die()
    {
        Debug.Log("游戏结束1");
        gameObject.SetActive(false);
        LevelFailed();
    }

    // 随着玩家通关次数增加，逐步提升每关需要命中的目标数量，且提升速度是分阶段的，越到后面阶段增长越快。
    void CheckHowManyHit()
    {
        int i;
        for (i = 0; i <= 100; i++)
        {
            if (numberOfWinning >= (2 * i + i * (i - 1) / 2) && numberOfWinning < (2 * (i + 1) + (i + 1) * i / 2))
            {
                break;
            }
        }
        numberOfHit = numberOfWinning - (2 * i + i * (i - 1) / 2) + 3 + i;
        Debug.Log($"当前关卡需要命中的目标数量: {numberOfHit}");
    }



    // 显示所有正确的目标
    IEnumerator ShowAllTrue(GameObject tr, bool isHit = true)
    { 
        //显示目标
        float time = 0.1f;
        float t = 0;
        while (t < time)
        {
            t += Time.deltaTime;
            float factor = t / time;
            tr.transform.localScale = Vector3.Lerp(Vector3.one, new Vector3(0.5f, 0.5f, 0.5f), factor);
            yield return null;
        }
        time = 0.1f;
        t = 0;
        while (t < time)
        {
            t += Time.deltaTime;
            float factor = t / time;
            tr.transform.localScale = Vector3.Lerp(tr.transform.localScale, Vector3.one, factor);
            yield return null;
        }
        Image img = tr.GetComponent<Image>();
        img.sprite = GameManager.Instance.openedSprite;


        //img.color = GameManager.Instance.openedSpriteColor;
        if(isHit)
        {
            tr.GetComponent<ChangePic>().isHit = isHit;
        } else
        {
            yield return new WaitForSeconds(0.5f);
            img.sprite = GameManager.Instance.defaultSprite;
            //img.color = GameManager.Instance.openedSpriteColor;
        }
    }

    // 检测鼠标点击位置是否命中目标
    public void ScreenMouseRay()
    {
        //处于翻转阶段不让点击
        if(isClick == false)
        {
            return;
        }
        if (!pickRandom.canClick)
            return;

        if (hitCount >= numberOfHit)
        {
            Debug.Log("游戏通关");
            hitCount = 0;
            numberOfWinning++;
            pickRandom.canClick = false;
            CheckHowManyHit();
            Invoke(nameof(ResetLevel), GameManager.Instance.resetLevel);
            //if (GameManager.Instance.showRemainedTilesCount)
            //    pickRandom.uiManager.countText.gameObject.SetActive(false);
            return;
        }

        if (!Input.GetMouseButtonDown(0) || isFail)
            return;

        Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Linecast(mouseWorldPos, mouseWorldPos, layer);

        if (hit.collider == null)
            return;

        var go = hit.collider.gameObject;
        var changePic = go.GetComponent<ChangePic>();
        if (hit.collider.CompareTag("FocusGameObject"))
        {
            if (changePic.CanChange && !changePic.isHit)
            {
                SoundManager.Instance.PlaySound(SoundManager.Instance.correct);
                ScoreManager.Instance.AddScore(1);

                Debug.Log("命中目标");
                StartCoroutine(ScaleChangeOnClick(go, true));
        
                changePic.isHit = true;
                hitCount++;

                var img = go.GetComponent<Image>();
                img.sprite = GameManager.Instance.openedSprite;
            }
            else if (!changePic.CanChange)
            {
                SoundManager.Instance.PlaySound(SoundManager.Instance.wrong);
                var gameTiles = GameObject.FindGameObjectWithTag("GameTiles");
                var animator = gameTiles.GetComponent<Animator>();
                animator.enabled = true;
                animator.Play("Shaking");
                isFail = true;
                StartCoroutine(ScaleChangeOnClick(go, false));
            }
        }
    }

    // 点击目标后缩放效果
    IEnumerator ScaleChangeOnClick(GameObject picture, bool isTrue)
    {
        float time = 0.1f;
        float t = 0;
        while (t < time)
        {
            t += Time.deltaTime;
            float factor = t / time;
            picture.transform.localScale = Vector3.Lerp(Vector3.one, new Vector3(0.5f, 0.5f, 0.5f), factor);
            yield return null;
        }
        time = 0.1f;
        t = 0;
        while (t < time)
        {
            t += Time.deltaTime;
            float factor = t / time;
            picture.transform.localScale = Vector3.Lerp(picture.transform.localScale, Vector3.one, factor);
            yield return null;
        }
        picture.transform.localScale = Vector3.one;

        if (!isTrue)
        {
            //picture.GetComponent<Image>().color = GameManager.Instance.wrongSelectionColor;
            picture.GetComponent<Image>().sprite = GameManager.Instance.wrongSprite;
            yield return new WaitForSeconds(0.1f);
            //GameObject[] trueList = GameObject.FindGameObjectsWithTag("FocusGameObject");
            foreach (GameObject pic in PicList)
            {
                if (pic.GetComponent<ChangePic>().enabled == true)
                {
                    StartCoroutine(ShowAllTrue(pic));
                }
            }
            Invoke(nameof(Die), 0.8f);
        }
    }

    void ResetLevel()
    {    
        pickRandom.ResetBack();
        LevelCompleted?.Invoke();
        SoundManager.Instance.PlaySound(SoundManager.Instance.levelComplete);
    }

    // 显示剩余未翻牌
    public void ShowTips()
    {
        isClick = false;
        // TODO 添加剩余显示次数
        foreach (GameObject picNode in PicList)
        {
            ChangePic pic = picNode.GetComponent<ChangePic>();
            if (pic.enabled && !pic.isHit)
            {
                StartCoroutine(ShowAllTrue(picNode, false));
            }
        }
        Invoke("delaySetClick",1.3f);
    }

    public void delaySetClick()
    {
        isClick = true;
    }
}


